

/**
 * 详情对话框
 */
var InfoDlg = {
    data: {
        isSort: null,
        nodes: [],
    }
};


layui.use(['layer', 'form', 'table', 'admin', 'ax', 'treeTable'], function () {
    var $ = layui.$;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var treeTable = layui.treeTable;

    /**
     * 基础字典管理初始化
     */
    var Dict = {
        tableId: "dictTable",	//表格id
        condition: {
            searchWords: ""
        }
    };

    /**
     * 初始化表格的列
     */
    Dict.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {title: '字典名称', field: 'name', visible: true, width: '15%'},
            {title: '字典key', field: 'dictKey', visible: true, width: '15%'},
            {title: '字典value', field: 'dictValue', visible: true, width: '15%'},
            {title: '状态', field: 'state', width: '7%', templet:function (d) {
                var str = '<input value="'+d.id+'" type="checkbox" name="state" lay-skin="switch" lay-filter="dictSwitch" lay-text="开启|关闭">';
                if(d.state == 1 && d.pid == '0'){
                    str = '<input value="'+d.id+'" type="checkbox" name="state" lay-skin="switch" lay-filter="dictSwitch" lay-text="开启|关闭" checked disabled>';
                }else {
                    str = '<input value="'+d.id+'" type="checkbox" name="state" lay-skin="switch" lay-filter="dictSwitch" lay-text="开启|关闭" checked>';
                }
                return str;
            }},
            {title: '更新时间', field: 'updateTime', visible: true, width: '12%'},
            {title: '修改人', field: 'updateUser', visible: true, width: '9%'},
            {title: '字典的描述', field: 'description', visible: true, width: '15%'},
            {align: 'center', toolbar: '#task-table-toolbar', title: '操作', width: 120, fixed:'right'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Dict.search = function () {
        var where = {searchWords: $("#searchWords").val()};
        tableReload(where);
    };

    /**
     * 基础字典添加
     */
    Dict.toAdd = function () {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '添加基础字典',
            area: ['40%', '80%'],
            content: Lu.ctxPath + '/system/dict/toAdd',
            success: function(layero, index){
                var body = top.layer.getChildFrame('body', index);
                body.find('#dictTypeId').val($("#dictTypeId").val());
                body.find('#dictTypeName').val($("#dictTypeName").val());
            },
            end: function () {
                Lu.adminOpenEnd(admin, tableReload);
            }
        });
     };

    /**
     * 修改基础字典
     */
    Dict.toUpdate = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '修改基础字典',
            area: ['40%', '80%'],
            content: Lu.ctxPath + '/system/dict/toUpdate?id=' + data.id,
            success: function(layero, index){
                var body = top.layer.getChildFrame('body', index);
                body.find('#dictTypeId').val($("#dictTypeId").val());
                body.find('#dictTypeName').val($("#dictTypeName").val());
            },
            end: function () {
                Lu.adminOpenEnd(admin, tableReload);
            }
        });
     };

    /**
     * 点击删除
     */
    Dict.onDelete = function (id) {
        var operation = function () {
            var ajax = new $ax(Lu.ctxPath + "/system/dict/delete", function (data) {
                Lu.success("删除成功!");
                tableReload();
            }, function (data) {
                Lu.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", id);
            ajax.start();
        };
        Lu.confirm("是否刪除?", operation);
    };

    /**
     * 点击排序按钮
     *
     * @param data 点击按钮时候的行数据
     */
    Dict.onSortDict = function () {
        var isSort = encodeURIComponent('parent.InfoDlg.data.isSort');
        var nodes = encodeURIComponent('parent.InfoDlg.data.nodes');
        var treeUrl = encodeURIComponent('/system/dict/dictTree');
        layer.open({
            type: 2,
            title: '父级菜单',
            area: ['40%', '90%'],
            content: '/system/treeSort?isSort='+isSort+'&nodes='+nodes+'&treeUrl='+treeUrl+'',
            end: function () {
                var isSort = InfoDlg.data.isSort;
                var nodes = InfoDlg.data.nodes;
                if(isSort && nodes && isSort == 1){
                    //排序
                    var ajax = new $ax(Lu.ctxPath + "/system/dict/sort", function () {
                        Lu.success("排序成功!");
                        InfoDlg.data.isSort = null;
                        InfoDlg.data.nodes = null;
                        tableReload();
                    }, function (data) {
                        Lu.error("排序失败!" + data.responseJSON.message + "!");
                    });
                    ajax.set("nodes", JSON.stringify(nodes));
                    ajax.start();
                }
            }
        });
    };

    /**
     * 更新缓存
     * @param ids
     */
    Dict.onUpdateCache = function(data){
        var ids = [];
        $.each(data, function (index, d) {
            ids.push(d.id);
        });
        var ajax = new $ax(Lu.ctxPath + "/system/dictType/dictCache", function (data) {
            Lu.success("更新缓存成功!");
        }, function (data) {
            Lu.error("更新缓存失败!" + data.responseJSON.message + "!");
        });
        ajax.set("dictTypeId", $("#dictTypeId").val());
        ajax.set("dictIds", JSON.stringify(ids));
        ajax.start();
    };

    /**
     * 初始化表格
     */
    Dict.initTable = function (tableId, data) {
        return treeTable.render({
            elem: '#' + tableId,
            url: '/system/dict/treeTable?dictTypeId=' + $("#dictTypeId").val(),
            where: data,
            page: false,
            height: "full-98",
            cellMinWidth: 100,
            cols: Dict.initColumn(),
            treeColIndex: 1,
            treeSpid: "0",
            treeIdName: 'id',
            treePidName: 'pid',
            treeDefaultClose: true, //外层关闭
            treeLinkage: false      //内层关闭
        });
    };

    var tableReload = (data) => {
        Dict.initTable(Dict.tableId, data);
    };

    tableReload();

   // 搜索按钮点击事件
   $('#btnSearch').click(function () {
        Dict.search();
   });

   $("#btnAdd").click(function () {
       //打开添加页面
       Dict.toAdd();
   });

   $("#btnSort").click(function () {
      Dict.onSortDict();
   });


    // 全部展开
    $('#expandAll').click(function(){
        treeTable.expandAll('#' + Dict.tableId);
    });
    // 全部关闭
    $('#foldAll').click(function(){
        treeTable.foldAll('#' + Dict.tableId);
    });


    // 工具条点击事件
   table.on('tool(' + Dict.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'update') {
            Dict.toUpdate(data);
        } else if (layEvent === 'del') {
            Dict.onDelete(data.id);
        }
    });

    //修改状态
    form.on('switch(dictSwitch)', function(data){
        var id = data.value;
        var state = 0;
        if(data.elem.checked){
            state=1;
        }
        var ajax = new $ax(Lu.ctxPath + "/system/dict/updateState", function (data) {
        }, function (data) {
            Lu.error("操作失败！" + data.responseJSON.message)
        });
        ajax.set({id : id, state : state});
        ajax.start();
    });

});